import 'dart:math';

import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/charts_pie.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/close_device_status_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/closure/close_in_and_out_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class ClosureAllViewController extends GetxController {


  // 人员预约情况数据
  List<ChartData> questionData = [
    ChartData('园区工作人员', 0, const Color(0xFF5C6DFF)),
    ChartData('临时访客', 0, const Color(0xFFFD6B6B)),
    ChartData('第三方单位人员', 0, const Color(0xFFFFCE24)),
    ChartData('其他', 0, const Color(0xFFA5A9C8)),
  ];

  // 以前人员预约数据
  List<ChartData> oldQuestionDate = [
    ChartData('以前园区工作人员', 0, const Color(0xFF5C6DFF)),
    ChartData('以前临时访客', 0, const Color(0xFFFD6B6B)),
    ChartData('以前第三方单位人员', 0, const Color(0xFFFFCE24)),
    ChartData('以前其他', 0, const Color(0xFFA5A9C8)),
  ];

  // 车辆预约情况数据
  List<ChartData> carData = [
    ChartData('普通车辆	', 0, const Color(0xFF5C6DFF)),
    ChartData('危化车辆	', 0, const Color(0xFFFD6B6B)),
    ChartData('小型车辆', 0, const Color(0xFFFFCE24)),
    ChartData('其他', 0, const Color(0xFFA5A9C8)),
  ];

  // 以前车辆预约情况
  List<ChartData> oldCarData = [
    ChartData('以前普通车辆', 0, const Color(0xFF5C6DFF)),
    ChartData('以前危化车辆', 0, const Color(0xFFFD6B6B)),
    ChartData('以前小型车辆', 0, const Color(0xFFFFCE24)),
    ChartData('以前其他', 0, const Color(0xFFA5A9C8)),
  ];


  // 人员预约情况总数
  int questionTotal = 0;

  // 报警情况数据
  List<ChartData> riskData = [
    ChartData('类型1', 1, const Color(0xFF5C6DFF)),
    ChartData('类型2', 1, const Color(0xFFFD6B6B)),
    ChartData('类型3', 1, const Color(0xFFFFCE24)),
    ChartData('类型4', 1, const Color(0xffFF5C6D)),
  ];

  /// 折线图数据
  List<ChartSeries<PieData, String>> lineData = [];

  //进入数量 离开数量 白名单进入 白名单离开
  List<String> tableTitle = ['进入数量', '离开数量', '白名单进入', '白名单离开'];

  // 人车出入情况(近7日) 0:人员 1:车辆
  PersonCarType type = PersonCarType.person;


  // 人员出入情况数据
  List<String> personData = ['类型1', '类型2', '类型3','类型4','确认及时率','处置及时率'];

  /// 柱状图数据
  List<CartesianSeries<PieData, String>> barData = [];

  // 人员出入情况数据初始化
  void initBarData() {
    for(int i = 0; i < personData.length; i++) {
      final Random random = Random();
      if(i == 4 || i == 5) {
        barData.add(LineSeries<PieData, String>(
            dataSource: [
              PieData('11.17', 0),
              PieData('11.18', 0),
              PieData('11.19', 0),
              PieData('11.20', 0),
              PieData('11.21', 0),
              PieData('11.22', 0),
              PieData('11.23', 0),
            ],
            xValueMapper: (PieData data, _) => data.xData,
            yValueMapper: (PieData data, _) => data.yData,
            name: personData[i],
            markerSettings: const MarkerSettings(isVisible: true)
        ));
        continue;
      }
      barData.add(ColumnSeries<PieData, String>(
          dataSource: [
            PieData('11.17', 0),
            PieData('11.18', 0),
            PieData('11.19', 0),
            PieData('11.20', 0),
            PieData('11.21', 0),
            PieData('11.22', 0),
            PieData('11.23', 0),
          ],
          xValueMapper: (PieData data, _) => data.xData,
          yValueMapper: (PieData data, _) => data.yData,
          name: personData[i]
      ));
    }
    update(['pie']);
  }


  /// 设备状态统计数据
  CloseDeviceStatusEntity? closeDeviceStatusEntity = CloseDeviceStatusEntity();

  // 设备状态统计数据
  void getDeviceData() async {
    final res = await HttpUtil().generateGetRequest<Map<String,dynamic>>(Interface.getEquipmentStatusCount).execute();

    res.onSuccess((result) {
      if(result.data != null) {
        closeDeviceStatusEntity =  CloseDeviceStatusEntity.fromJson(result.data!);
        update(['status']);
      }
    });

  }


  // 人员预约情况数据
  void getPersonData() async {
    final res = await HttpUtil().generateGetRequest<Map<String,dynamic>>(Interface.addReservation,queryParameters: {
      'dateType': 0,
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        questionData[0].y = result.data!['parkPersonnel'] as num;

        questionData[1].y = result.data!['temporaryVisitor'] as num;

        questionData[2].y = result.data!['thirdPartyUnits'] as num;

        questionData[3].y = result.data!['other'] as num;

        oldQuestionDate[0].y = result.data!['lastParkPersonnel'] as num;

        oldQuestionDate[1].y = result.data!['lastTemporaryVisitor'] as num;

        oldQuestionDate[2].y = result.data!['lastThirdPartyUnits'] as num;

        oldQuestionDate[3].y = result.data!['lastOther'] as num;

        questionTotal = questionData.map((e) => e.y).reduce((value, element) => value + element).toInt();

        /// 如果总数为0，那么就全部显示为1,优化显示效果
        if(questionTotal == 0) {
          for (var element in questionData) {
            element.y = 1;
          }
        }
        update(['car']);
      }
    });
  }


  // 车辆预约情况数据
  void getCarData() async {
    final res = await HttpUtil().generateGetRequest<Map<String,dynamic>>(Interface.addVehicleReservation,queryParameters: {
      'dateType': 0,
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        carData[0].y = result.data!['ordinaryVehicles'] as num;

        carData[1].y = result.data!['dangerousVehicles'] as num;

        carData[2].y = result.data!['smallVehicles'] as num;

        carData[3].y = result.data!['other'] as num;

        oldCarData[0].y = result.data!['lastOrdinaryVehicles'] as num;

        oldCarData[1].y = result.data!['lastDangerousVehicles'] as num;

        oldCarData[2].y = result.data!['lastSmallVehicles'] as num;

        oldCarData[3].y = result.data!['lastOther'] as num;

        questionTotal = carData.map((e) => e.y).reduce((value, element) => value + element).toInt();

        /// 如果总数为0，那么就全部显示为1,优化显示效果
        if(questionTotal == 0) {
          for (var element in carData) {
            element.y = 1;
          }
        }
        update(['car']);
      }
    });
  }

  /// 人员出入情况数据
  List<CloseInAndOutEntity> personInOutData = [];

  // 人员出入情况数据
  void getPersonInOutData() async {
    final res = await HttpUtil().generateGetRequest<List<CloseInAndOutEntity>>(Interface.getPersonnelAccess,queryParameters: {
      'dateType': 0,
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        personInOutData = result.data!;
        // 测试数据
        personInOutData.clear();
        initQuestionData();
      }
    });
  }

  // 人员出入情况数据初始化
  void initQuestionData() {
    if(personInOutData.isEmpty) {
      lineData.clear();
      // 如果没数据，那么就添加假数据
      for(int i = 0; i < tableTitle.length; i++) {
        lineData.add(SplineSeries<PieData, String>(
          dataSource: [],
          xValueMapper: (PieData data, _) => data.xData,
          yValueMapper: (PieData data, _) => data.yData,
          name: tableTitle[i],
        ));
      }
      update(['car']);
      return;
    }
    for(int i = 0; i < tableTitle.length; i++) {
      lineData.add(SplineSeries<PieData, String>(
        dataSource: personInOutData.map((e) => PieData(e.dateTime!,_type(i,e))).toList(),
        xValueMapper: (PieData data, _) => data.xData,
        yValueMapper: (PieData data, _) => data.yData,
        name: tableTitle[i],
      ));
    }
    update(['car']);
  }

  // 车辆出入情况数据
  void getCarInOutData() async {
    final res = await HttpUtil().generateGetRequest<List<CloseInAndOutEntity>>(Interface.getVehicleAccess,queryParameters: {
      'dateType': 0,
    }).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        personInOutData = result.data!;
        initQuestionData();
      }
    });
  }

  // ['进入数量', '离开数量', '白名单进入', '白名单离开']
  num _type(int i ,CloseInAndOutEntity close) {
   switch(i) {
     case 0:
       return close.advance ?? 0;
     case 1:
       return close.goOut ?? 0;
     case 2:
       return close.whiteAdvance ?? 0;
     case 3:
       return close.whiteGoOut ?? 0;
     default:
       return 0;
   }
  }

  @override
  void onInit() {
    super.onInit();
    initBarData();
    getDeviceData();
    getPersonData();
    getPersonInOutData();
  }

}

/// 人车出入情况枚举
enum PersonCarType {
  /// 人员
  person,

  /// 车辆
  car,
}
